package com.example.fengyungo_user.activity.me;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fengyungo_user.R;
import com.example.fengyungo_user.activity.BaseActivity;
import com.example.fengyungo_user.activity.main.MainActivity;
import com.example.fengyungo_user.constant.DriverConstant;
import com.example.fengyungo_user.constant.MessageConstant;
import com.example.fengyungo_user.constant.ResultConstant;
import com.example.fengyungo_user.constant.UserConstant;
import com.example.fengyungo_user.domain.DriverWithNumber;
import com.example.fengyungo_user.domain.Message;
import com.example.fengyungo_user.domain.User;
import com.example.fengyungo_user.utils.ActivityCollector;
import com.example.fengyungo_user.utils.OkHttpUtils;
import com.example.fengyungo_user.utils.SharedPreferencesUtils;
import com.example.fengyungo_user.utils.ThreadPoolUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DriverDetailActivity extends BaseActivity {

    /**
     * 司机信息
     */
    private DriverWithNumber driver;

    private ImageButton backBtn;

    private Button selectBtn;

    private TextView nicknameTv;

    private TextView sexTv;

    private TextView phoneTv;

    private TextView mailTv;

    private RatingBar ratingBar;

    private ImageView avatarImg;

    private ProgressBar progressBar;

    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver_detail);

        // 获取司机信息
        Intent intent = getIntent();
        driver = (DriverWithNumber) intent.getSerializableExtra(DriverConstant.DRIVER);
        String keyForDetail = intent.getStringExtra(DriverConstant.KEY_FOR_DRIVER_DETAIL);

        // 用户信息（本人）
        user = SharedPreferencesUtils.getUserInfo(this);

        initControls();
        if (keyForDetail != null && keyForDetail.equals(DriverConstant.NOT_SELECT)) {
            selectBtn.setVisibility(View.GONE);
        }

        // 填充司机信息
        setDriverInfo();

        // 返回
        backBtn.setOnClickListener(view -> finish());

        // 选择司机
        selectBtn.setOnClickListener(view -> {
            selectThisDriver();
            // 通知司机
            // 建立聊天
            addMessageList();
            // 发送接单信息给接单者
            sendMessage();
        });
    }

    /**
     * 生成通知
     *
     * @return Message
     */
    private Message generateMessage() {
        DateTimeFormatter formatterForId;
        DateTimeFormatter formatterForSendTime;
        String sendTime = "2000-01-01 01:00:00";
        String timeForId = "2000-01-01 01:00:00";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            // 根据发送时间与用户id生成消息id
            formatterForId = DateTimeFormatter.ofPattern("MMddHHmmss");
            formatterForSendTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            sendTime = now.format(formatterForSendTime);
            timeForId = now.format(formatterForId);
        }

        String content = "你成功接受了【" + user.getUserNickname() + "】从【"
                + driver.getBegin() + "】到【" + driver.getEnd() + "】的订单。";

        Message message = new Message();
        message.setReceiverId(driver.getId());
        message.setContent(content);
        message.setSenderId(MessageConstant.U_SYSTEM_ID);
        message.setSendTime(sendTime);
        message.setMessageId(driver.getId() + timeForId);
        return message;
    }

    /**
     * 发送信息
     */
    private void sendMessage() {
        Runnable runnable = () -> {
            try {
                String url = MessageConstant.URL + "/addMessage";
                Message message = generateMessage();

                String json = com.alibaba.fastjson.JSONObject.toJSONString(message);

                String responseData = OkHttpUtils.post(url, json);

                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                if (code == ResultConstant.SUCCESS) {

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DriverDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DriverDetailActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 发起聊天
     */
    private void addMessageList() {
        Runnable runnable = () -> {
            try {
                String url = MessageConstant.URL + "/addMessageList/" + driver.getId() + "/" + MessageConstant.U_SYSTEM_ID;
                String responseData = OkHttpUtils.post(url, "");

                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                if (code == ResultConstant.SUCCESS) {

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DriverDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DriverDetailActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 选择该司机
     */
    private void selectThisDriver() {
        progressBar.setVisibility(View.VISIBLE);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String url = UserConstant.URL_USER_USER + "/" + driver.getId() + "/" + driver.getNumber();
                try {
                    String responseData = OkHttpUtils.put(url, "");
                    JSONObject jsonObject = new JSONObject(responseData);
                    int code = jsonObject.getInt(ResultConstant.CODE);
                    String msg = jsonObject.getString(ResultConstant.MSG);
                    if (code == ResultConstant.SUCCESS) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(DriverDetailActivity.this, DriverConstant.SELECT_DRIVER, Toast.LENGTH_SHORT).show();
                                ActivityCollector.finishOtherActivity(MainActivity.class);
                                // todo 返回到上一个fragment时需要自动刷新
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(DriverDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(DriverDetailActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 设置司机信息
     */
    private void setDriverInfo() {
        nicknameTv.setText(driver.getNickname());
        sexTv.setText(driver.getSex());
        phoneTv.setText(driver.getPhone());
        mailTv.setText(driver.getMail());
        ratingBar.setRating(driver.getCredit());
    }

    private void initControls() {
        backBtn = findViewById(R.id.btn_back);
        selectBtn = findViewById(R.id.btn_select);

        nicknameTv = findViewById(R.id.tv_nickname);
        sexTv = findViewById(R.id.tv_sex);
        phoneTv = findViewById(R.id.tv_phone);
        mailTv = findViewById(R.id.tv_mail);

        ratingBar = findViewById(R.id.rating);

        avatarImg = findViewById(R.id.avatar);

        progressBar = findViewById(R.id.progress_bar);
    }
}